package org.example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class FlinkWordCount {

    public static void main(String... args){
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        List<String> list = new ArrayList<>();
        list.add("hello world!");
        list.add("hello java");
        list.add("hello flink");
        DataSource<String> source =  env.fromCollection(list);
        FlatMapOperator<String,Tuple2<String,Long>> flatMapOperator = source.flatMap(new FlatMapFunction<String, Tuple2<String,Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word: words) {
                    collector.collect(Tuple2.of(word,1L));
                }
            }
        }).returns(Types.TUPLE(Types.STRING,Types.LONG));


        //根据第0个索引进行分组
       UnsortedGrouping<Tuple2<String,Long>> unsortedGrouping =  flatMapOperator.groupBy(0);
       //对索引下标为1的进行相加，对分组后相同key，中value相加
       AggregateOperator<Tuple2<String,Long>>  aggregateOperator = unsortedGrouping.sum(1);
       //打印输出
        try {
            aggregateOperator.print();
        }catch (Exception e){
            e.printStackTrace();
        }


//        source.flatMap( (String line, Collector<Tuple2<String, Long>> out) -> {
//            String[] words = line.split(" ");
//            for (String word: words) {
//                out.collect(Tuple2.of(word,1L));
//            }
//        });
    }
}
